package com.swordget.service.impl;

import com.swordget.dao.DataVerifyDao;
import com.swordget.entity.po.DataVerifyPo;
import com.swordget.exception.VerifyFailException;
import com.swordget.service.DataVerifyService;
import com.swordget.service.TableDefinitionService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: David
 * @Date: Created in 18:07 2020/4/9
 * @Description: ${DESCRIPTION}
 * @Modified By:
 * @Version: ${VERSION}
 */
@Service
public class DataVerifyServiceImp implements DataVerifyService {

    private TableDefinitionService tableDefinitionService;

    private DataVerifyDao dataVerifyDao;

    /**
     * DataVerifyServiceImp log
     */
    private final static Logger LOG = LoggerFactory.getLogger(DataVerifyServiceImp.class);

    @Autowired
    public DataVerifyServiceImp(TableDefinitionService tableDefinitionService, DataVerifyDao dataVerifyDao) {
        this.tableDefinitionService = tableDefinitionService;
        this.dataVerifyDao = dataVerifyDao;
    }

    @Override
    public void verify(String tableId, String tableName, String columns, String values, String keyValue) {
        String verifyCommand = this.getVerifyCommand(tableId);
        if (StringUtils.isBlank(verifyCommand)) {
            return;
        }
        try {
            DataVerifyPo dataVerifyPo = dataVerifyDao.verify(tableName, verifyCommand, columns, values, keyValue);
            if (dataVerifyPo != null) {
                throw new VerifyFailException("校验失败" + dataVerifyPo.getMark() + dataVerifyPo.getReason());
            }
        } catch (Exception e) {
            LOG.error("程序执行过程中出现异常", e);
            throw new VerifyFailException("校验失败", e);
        }
    }

    @Override
    public List<DataVerifyPo> verify(String tableId, String tableName, String tableNameTmp, String importId) {
        String verifyCommand = this.getVerifyCommand(tableId);
        if (StringUtils.isBlank(verifyCommand)) {
            return null;
        }
        try {
            return dataVerifyDao.verify(tableName, tableNameTmp, verifyCommand, importId);
        } catch (Exception e) {
            LOG.error("程序执行过程中出现异常", e);
            throw new VerifyFailException("校验失败", e);
        }

    }

    private String getVerifyCommand(String tableId) {
        //获取校验文件位置
        String checkFilePath = tableDefinitionService.getCheckFilePath(tableId);
        //不强制要求使用校验文件
        if (StringUtils.isBlank(checkFilePath)) {
            return "";
        }
        //读取文件获取校验语句
        StringBuilder builder = new StringBuilder();
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(checkFilePath))) {
            int readNum = 0;
            byte[] bytes = new byte[1024];
            while ((readNum = inputStream.read(bytes)) > 0) {
                builder.append(new String(bytes, 0, readNum, StandardCharsets.UTF_8));
            }
        } catch (FileNotFoundException e) {
            LOG.error("程序执行过程中出现异常", e);
            throw new VerifyFailException("校验文件不存在");
        } catch (IOException e) {
            LOG.error("程序执行过程中出现异常", e);
            throw new VerifyFailException("无法读取校验文件", e);
        }
        return builder.toString();
    }
}
